package com.rfsp.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

/**
 * tokenTool
 * @author leopard
 *
 */
public class JwtUtil {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String TOKEN_SECRET = "jwtsecretrfsp";//密钥盐
    private static final String ISS = "rfsp";

    // 过期时间是3600秒，既是1个小时
    //public static final long EXPIRE_TIME = 24 * 3600 * 1000;
    public static final long EXPIRE_TIME = 5 * 1000;

    // 选择了记住我之后的过期时间为30天
    public static final long EXPIRE_REMEMBER = 30*24*3600*1000L;

    /**
     * 创建token
     * 注：如果是根据可变的唯一值来生成，唯一值变化时，需重新生成token
     * @param userCode
     * @param isRememberMe
     * @return
     */
    public static String getToken(Long id,Long orgId, String userCode, boolean isRememberMe) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + (isRememberMe ? EXPIRE_REMEMBER : EXPIRE_TIME));
            token = JWT.create()
                    .withIssuer(ISS)
                    .withClaim("userId", id)
                    .withClaim("orgId", orgId)
                    .withClaim("userCode", userCode)
                    .withClaim("isVip", "")
                    .withExpiresAt(expiresAt)
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e){
//            LogUtil logger = LogUtil.getLogger(JwtUtil.class);
//            logger.error(e.getMessage());
        }
        return token;

    }


    /**
     * getUserCode
     * @param token
     * @return
     */
    public static DecodedJWT getJWT(String token) throws JWTVerificationException{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer(ISS).build();

        DecodedJWT jwt = verifier.verify(token.replaceAll(TOKEN_PREFIX, ""));

        /*try {
            jwt = verifier.verify(token.replaceAll(TOKEN_PREFIX, ""));
        }catch(JWTVerificationException e){
            e.printStackTrace();
            //throw new RuntimeException("4011");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/

        return jwt;
    }

    /**
     * 签名验证
     * @param token
     * @return
     */
    public static boolean verify(String token) throws JWTVerificationException {
//        LogUtil logger = LogUtil.getLogger(JwtUtil.class);

            DecodedJWT jwt = JwtUtil.getJWT(token.replaceAll(TOKEN_PREFIX, ""));
//            logger.info("认证通过：");
//            logger.info("issuer:  " + jwt.getIssuer());
//            logger.info("usercode: " + jwt.getClaim("userCode").asString());
//            logger.info("过期时间： " + jwt.getExpiresAt());
            return true;

    }

    /**
     * getUserCode
     * @param token
     * @return
     */
    public static Long getUserId(String token){
        if(token==null || "".equals(token)){
            return null;
        }
        DecodedJWT jwt = JwtUtil.getJWT(token.replaceAll(TOKEN_PREFIX, ""));
        if(jwt==null){
            return null;
        }
        return jwt.getClaim("userId").asLong();
    }

    /**
     * getUserCode
     * @param token
     * @return
     */
    public static String getUserCode(String token){
        if(token==null || "".equals(token)){
            return null;
        }
        DecodedJWT jwt = JwtUtil.getJWT(token.replaceAll(TOKEN_PREFIX, ""));
        if(jwt==null){
            return null;
        }
        return jwt.getClaim("userCode").asString();
    }


    /**
     * getOrgId
     * @param token
     * @return
     */
    public static Long getOrgId(String token){
        if(token==null || "".equals(token)){
            return null;
        }
        DecodedJWT jwt = JwtUtil.getJWT(token.replaceAll(TOKEN_PREFIX, ""));
        if(jwt==null){
            return null;
        }
        return jwt.getClaim("orgId").asLong();
    }
}
